package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.CustomerSerivce;
import com.atguigu.jxc.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CustomerSerivceImpl implements CustomerSerivce {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LogService logService;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String customerName) {
        Map<String,Object> map = new HashMap<>();

        page = page == 0 ? 1 : page;
        int offSet = (page - 1) * rows;
        List<Customer> customers = customerDao.list(offSet, rows, customerName);

        logService.save(new Log(Log.SELECT_ACTION,"分页查询客户信息"));

        map.put("total", customerDao.getCustomerCount(customerName));
        map.put("rows", customers);
        return map;
    }

    @Override
    public ServiceVO save(Customer customer) {
        // 客户ID为空时，说明是新增操作，需要先判断用户名是否存在
        if(customer.getCustomerId() == null){

            Customer exCustomer = customerDao.findCustomerByName(customer.getCustomerName());
            if (exCustomer != null) {
                return new ServiceVO(ErrorCode.ACCOUNT_EXIST_CODE, ErrorCode.ACCOUNT_EXIST_MESS);
            }

            customerDao.addCustomer(customer);
            logService.save(new Log(Log.INSERT_ACTION,"添加客户:"+customer.getCustomerName()));
        } else {
            customerDao.updateCustomer(customer);
            logService.save(new Log(Log.UPDATE_ACTION,"修改客户:"+customer.getCustomerName()));
        }

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    @Override
    public ServiceVO delete(String[] id) {
        List<Customer> customerList = customerDao.getCustomerByIds(id);
        for (Customer customer : customerList) {
            String customerName = customer.getCustomerName();
            logService.save(new Log(Log.DELETE_ACTION, "删除客户:" + customerName));
        }

        customerDao.deleteCustomer(id);

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }
}
